package com.huika.renrench.control.my.account;

import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.android.volley.Response.Listener;
import com.google.gson.reflect.TypeToken;
import com.huika.lib.validation.EditTextValidator;
import com.huika.lib.validation.ValidationModel;
import com.huika.renrench.GlobalApp;
import com.huika.renrench.R;
import com.huika.renrench.config.Constant;
import com.huika.renrench.config.UrlConstants;
import com.huika.renrench.control.common.base.BaseAct;
import com.huika.renrench.control.login.validations.PhoneNumberValidation;
import com.huika.renrench.control.login.validations.VerifyNumberValidation;
import com.huika.renrench.control.my.event.BindPhoneEvent;
import com.huika.renrench.http.FormResultRequest;
import com.huika.renrench.http.JSONWrapAjaxParams;
import com.huika.renrench.http.RequestResult;
import com.huika.renrench.support.bean.UserModel;
import com.huika.renrench.utils.LoginUtils;
import com.huika.renrench.utils.PreferencesHelper;
import com.huika.renrench.view.TitleBarHelper;
import com.huika.renrench.view.clearedit.ClearableEditText;

import de.greenrobot.event.EventBus;

/**
 * @ClassName: SetNewPhoneActivity
 * @说明:绑定新手机
 * @author zwy
 * @date 2015年6月4日 上午11:31:46
 */
public class SetNewPhoneActivity extends BaseAct {
	private ClearableEditText etPhone;
	private ClearableEditText etVerfy;
	private TextView btnVerfy;
	private Button btnSubmit;

	private EditTextValidator phoneValidator;
	private EditTextValidator editTextValidator;
	private String phone;
	private String account;
	private String userId;
	private String key;

	@Override
	public void setRootView() {
		setContentView(R.layout.activity_set_newphone);
	}

	@Override
	protected void initData() {
		UserModel userModel = GlobalApp.userModel;
		account = userModel.getAccount();
		userId = userModel.getUserId();
		key = getIntent().getStringExtra("key");
	}

	@Override
	protected void initWidget() {
		TitleBarHelper titleBarHelper = new TitleBarHelper(this, -1);
		titleBarHelper.setLeftMsg(R.string.left_back);
		if ("000000".equals(key)) {
			titleBarHelper.setTitleMsg("绑定手机号");
		}else{
			titleBarHelper.setTitleMsg("绑定新手机");
		}
		etPhone = (ClearableEditText) findViewById(R.id.et_phone_asnp);
		etVerfy = (ClearableEditText) findViewById(R.id.et_verfy_asnp);
		btnVerfy = (TextView) findViewById(R.id.btn_verfy_asnp);
		btnSubmit = (Button) findViewById(R.id.btn_submit_asnp);
		btnVerfy.setOnClickListener(this);
		btnSubmit.setOnClickListener(this);
		etPhone.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if (s.length() > 0) {
					if (!s.toString().substring(0, 1).equals("1")) {
						etPhone.setText("");
					} else if (s.length() > 1 && !s.toString().substring(1, 2).matches("[345789]")) {
						etPhone.setText("1");
						etPhone.setSelection(etPhone.length());
					}
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});
		phoneValidator = new EditTextValidator(this).add(new ValidationModel(etPhone, new PhoneNumberValidation())).execute();
		editTextValidator = new EditTextValidator(this).add(new ValidationModel(etVerfy, new VerifyNumberValidation())).execute();
	}

	@Override
	public void widgetClick(View v) {
		switch (v.getId()) {
		case R.id.btn_verfy_asnp:
			verfyNet();
			break;
		case R.id.btn_submit_asnp:
			submit();
			break;
		default:
			break;
		}
	}

	private void verfyNet() {
		if (phoneValidator.validate()) {
			showLoadingDialog("");
			phone = getInputStr(etPhone);
			FormResultRequest<String> request = new FormResultRequest<String>(UrlConstants.GETMSGBINDNEWPHONEGETCODEREQ, codeListener, this,
					new TypeToken<RequestResult<String>>() {
					}.getType());
			JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
			ajaxParams.putStringTypeParam("userId", userId);
			ajaxParams.putStringTypeParam("phone", phone);
			ajaxParams.putStringTypeParam("account", account);
			ajaxParams.putStringTypeParam("ip", GlobalApp.ip);
			ajaxParams.putStringTypeParam("mac", GlobalApp.mac);
			ajaxParams.putStringTypeParam("dev", Constant.DEV);
			request.setRequestParams(ajaxParams);
			executeRequest(request);
		}

	}

	private void submit() {
		if (phoneValidator.validate() && editTextValidator.validate()) {
			showLoadingDialog("");
			FormResultRequest<String> request = new FormResultRequest<String>(UrlConstants.BANDINGPHONE, verfyListener, this, new TypeToken<RequestResult<String>>() {
			}.getType());
			JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
			ajaxParams.putStringTypeParam("userId", userId);
			ajaxParams.putStringTypeParam("phone", phone);
			ajaxParams.putStringTypeParam("validateCode", getInputStr(etVerfy));
			ajaxParams.putStringTypeParam("key", key);
			ajaxParams.putStringTypeParam("ip", GlobalApp.ip);
			ajaxParams.putStringTypeParam("mac", GlobalApp.mac);
			ajaxParams.putStringTypeParam("dev", Constant.DEV);
			request.setRequestParams(ajaxParams);
			executeRequest(request);
		}
	}

	private Listener<RequestResult<String>> codeListener = new Listener<RequestResult<String>>() {
		@Override
		public void onResponse(RequestResult<String> arg0) {
			dismissLoadingDialog();
			showToastMsg(arg0.msg);
			btnVerfy.setClickable(false);
			new CountDownTimer(120000, 1000) {
				public void onTick(long millisUntilFinished) {
					btnVerfy.setTextColor(getResources().getColor(R.color.color_969696));
					btnVerfy.setText(String.format("%s秒", String.valueOf(millisUntilFinished / 1000)));
				}

				public void onFinish() {
					btnVerfy.setTextColor(getResources().getColor(R.color.color_38bdee));
					btnVerfy.setText("获取验证码");
					btnVerfy.setClickable(true);
				}
			}.start();
		}
	};
	private Listener<RequestResult<String>> verfyListener = new Listener<RequestResult<String>>() {
		@Override
		public void onResponse(RequestResult<String> arg0) {
			if (arg0.flag == 1) {
				GlobalApp.userModel.setPhone(phone);
				LoginUtils loginUtils = new LoginUtils(SetNewPhoneActivity.this);
				PreferencesHelper.setString(PreferencesHelper.KEY_LOGIN_NAME, phone);
				loginUtils.autoLogin();
				EventBus.getDefault().post(new BindPhoneEvent(1));
				aty.finish();
			}else{
				dismissLoadingDialog();
			}
			showToastMsg(arg0.msg);
		}
	};

}
